<template>
  <el-row class="login-row" type="flex" justify="center" align="middle">
    <el-col
      :xs="{ span: 20 }"
      :sm="{ span: 12 }"
      :md="{ span: 10 }"
      :lg="{ span: 8 }"
      :offset="0"
    >
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <span><!-- card title --></span>
        </div>
        <!-- card body -->
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model.number="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >登录</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
export default {
  data() {
    var checkName = (rule, value, callback) => {
      value = value + "";
      if (!value) {
        return callback(new Error("账号不能为空"));
      }
      console.log(value, value.length);
      if (value.length < 2) {
        return callback(new Error("账号名称不能少于两个字符"));
      }
      return callback(); //验证通过
    };
    var validatePass = (rule, value, callback) => {
      if (value.trim() === "") {
        return callback(new Error("请输入密码"));
      }
      return callback();
    };
    return {
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ validator: checkName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          this.$store.dispatch("user/userLoginAct", this.ruleForm); //触发登录的异步action
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss">
.login-row {
  height: 100vh;
}
</style>
